﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Microsoft.Win32;
using System.Windows;
using System.Xml;

namespace SHomeWorkshop.LunarMind.Commands
{
    /// <summary>
    /// 以此类为模板，制作自定义命令类
    ///     共需要修改１０处！！！
    /// ==============================
    /// 
    /// 向下选取命令。
    /// ★①，修改类名。
    /// </summary>
    public static class HorizontalListSelectDownCommand
    {
        private static RoutedUICommand routedUICmd;//创建私有字段

        public static RoutedUICommand RoutedUICmd//创建只读静态属性
        {
            get { return routedUICmd; }
        }

        /// <summary>
        /// ★②，修改静态构造方法名。
        /// </summary>
        static HorizontalListSelectDownCommand()//类型构造器
        {
            //★③，修改两个字符串参数名。★④以及第三个参数的类型名。
            routedUICmd = new RoutedUICommand(
                "HorizontalListSelectDownCommand",
                "HorizontalListSelectDownCommand",
                typeof(HorizontalListSelectDownCommand),//创建RoutedUICommand对象
                new InputGestureCollection() 
                { 
                    //★⑤，修改此处两个参数，以便挂接快捷键。
                    new KeyGesture(Key.Down,ModifierKeys.None,"Down")
                });

            cmdBinding.Command = routedUICmd;
            cmdBinding.CanExecute += new CanExecuteRoutedEventHandler(cmdBinding_CanExecute);
            cmdBinding.Executed += new ExecutedRoutedEventHandler(cmdBinding_Executed);
        }

        private static CommandBinding cmdBinding = new CommandBinding();

        public static CommandBinding CmdBinding
        {
            get { return cmdBinding; }
        }

        static void cmdBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            //★⑦，修改此方法的实现。

            Execute();
        }

        internal static void Execute()
        {
            if (Globals.MainWindow.SelectedTitleImage != null)
            {
                Globals.MainWindow.SelectedTitleImage.MasterTitle.SelectOnlySelf();
                return;
            }

            if (Globals.SelectedTitlesList.Count <= 0)
            {
                var selComment = Globals.MainWindow.SelectedComment;
                if (selComment != null && selComment.MasterTitle != null)
                {
                    selComment.MasterTitle.SelectOnlySelf(); return;
                }

                var selPictureBox = Globals.MainWindow.SelectedPictureBox;
                if (selPictureBox != null && selPictureBox.MasterTitle != null)
                {
                    selPictureBox.MasterTitle.SelectOnlySelf(); return;
                }

                Globals.MainWindow.RootTitle.SelectOnlySelf();
            }
            else if (Globals.SelectedTitlesList.Count > 1)
            {
                Title mainSelectedTitle = null;
                foreach (Title t in Globals.SelectedTitlesList)
                {
                    if (t.IsMainSelectedTitle)
                    {
                        mainSelectedTitle = t;
                    }
                }

                if (mainSelectedTitle == null)
                {
                    Globals.MainWindow.RootTitle.SelectOnlySelf();
                }
                else
                {
                    if (mainSelectedTitle.IsFixed)
                    {
                        Title higher = mainSelectedTitle.GetHigherLvelTitle();
                        if (higher != null)
                        {
                            higher.SelectOnlySelf();
                        }
                        else
                        {
                            Globals.MainWindow.RootTitle.SelectOnlySelf();
                        }
                    }
                    else
                    {
                        mainSelectedTitle.SelectOnlySelf();
                    }
                }
            }
            else
            {
                //分情况：
                Title t = Globals.SelectedTitlesList[0];

                //对横向列表来说，下方向键总是同一个行为：如果有下级，选定下级中第一个，如果没有，选定同级下一个，如果连同级下一个都没有，什么都不做。

                if (t == Globals.MainWindow.RootTitle || t.HigherLevelTitleID == Globals.MainWindow.RootTitle.ID)//根标题或一级标题，选中第一个下级标题。
                {
                    List<Title> lowerTitles = t.LowerLevelTitles;
                    if (lowerTitles.Count > 0)
                    {
                        lowerTitles[0].SelectOnlySelf();
                        return;
                    }
                }

                Title subRoot;//根据所属一级标题所占的横向区域，按纵坐标来找，这样更方便实现。

                Title higher = t.GetHigherLvelTitle();
                while (higher.HigherLevelTitleID != Globals.MainWindow.RootTitle.ID)
                {
                    higher = higher.GetHigherLvelTitle();
                    if (higher == null) break;
                }

                if (higher == null) return;

                subRoot = higher;

                higher = subRoot.GetHigherLvelTitle();
                if (higher.ID != Globals.MainWindow.RootTitle.ID) return;

                double left = subRoot.LeftTop.X;
                double right;

                #region 有必要按顺序，否则会导致快捷键失灵。
                List<Title> subRoots = higher.LowerLevelTitles;
                var rightSubRoots = new List<Title>();
                var leftSubRoots = new List<Title>();

                foreach (var child in subRoots)
                {
                    if (child.Direction == TitleDirection.Left)
                    {
                        leftSubRoots.Add(child);
                    }
                    else rightSubRoots.Add(child);
                }

                subRoots.Clear();
                subRoots.AddRange(rightSubRoots);
                subRoots.AddRange(leftSubRoots); 
                #endregion

                int index = subRoots.IndexOf(subRoot);
                if (index == subRoots.Count - 1)//最后一个
                {
                    right = double.MaxValue;
                }
                else
                {
                    right = subRoots[index + 1].LeftTop.X;
                }


                List<Title> titles = new List<Title>();

                foreach (UIElement ue in Globals.MainWindow.mainCanvas.Children)
                {
                    Title title = ue as Title;
                    if (title == null) continue;
                    if (title.IsFixed) continue;
                    if (title.LeftTop.X > left && title.LeftTop.X + title.ActualWidth < right && title.LeftTop.Y > t.LeftTop.Y && title.BeCollapsed == false)
                    {
                        titles.Add(title);
                    }
                }

                //按纵坐标排序，找出第一个即可。
                if (titles.Count > 0)
                {
                    titles.Sort(new CompareTitleByTop());
                    titles[0].SelectOnlySelf();
                }
            }
        }

        static void cmdBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            //★⑧，修改此方法的实现。
            e.CanExecute = true;//总是可用。
        }
    }
}
